# -*- coding: utf-8 -*-
import hashlib
import json
import time

import requests
import xmltodict
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://epay.cdzbtpay.com/cgi-bin/netpayment/pay_gate.cgi'

APP_CONF = {
    '810001110013240': {
        'API_KEY': '58678e4d81dde663c8dd9fc196913ad8',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _gen_sign_str(p_dict):
    return 'apiName={}&apiVersion={}&platformID={}&merchNo={}&orderNo={}&tradeDate={}&amt={}&merchUrl={}&merchParam={}&tradeSummary={}'.format(
        p_dict['apiName'],
        p_dict['apiVersion'],
        p_dict['platformID'],
        p_dict['merchNo'],
        p_dict['orderNo'],
        p_dict['tradeDate'],
        p_dict['amt'],
        p_dict['merchUrl'],
        p_dict['merchParam'],
        p_dict['tradeSummary'],
    )


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zbtpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 1  网银
# 4.  支付宝扫码
# 5.  微信扫码
# 6.  QQ扫码
# 8.  京东扫码
# 9.  支付宝H5(WAP_PAY_B2C)
# 10. 支付宝WAP(WAP_PAY_B2C)
# 12. 平台快捷支付(WEB_PAY_B2C)
# 13  微信H5(WAP_PAY_B2C)
# 14  QQ WAP(WAP_PAY_B2C)
# 15  QQ H5(WAP_PAY_B2C)
# 17.银联扫码
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '13'
    elif service == 'alipay':
        payType = '9'
    elif service == 'qq':
        payType = '15'
    else:
        payType = '12'
    return payType


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    p_dict = {
        'apiName': 'WAP_PAY_B2C',
        'apiVersion': '1.0.0.0',
        'platformID': mch_id,
        'merchNo': mch_id,
        'orderNo': str(pay.id),
        'tradeDate': time.strftime("%Y%m%d"),
        'amt': str(pay_amount),
        'merchUrl': '{}/pay/api/{}/zbtpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id).replace(
            'http://', 'http://zmkdkb.top/'),
        'merchParam': '123',
        'tradeSummary': 'charge',
    }
    sign_str = _gen_sign_str(p_dict)
    p_dict['signMsg'] = _generate_sign(sign_str + key)
    p_dict['choosePayType'] = _get_pay_type(service)
    _LOGGER.info("zbtpay create date: %s", p_dict)
    html_text = _build_form(p_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zbtpay notify data: %s", data)
    _LOGGER.info("zbtpay notify body: %s", request.body)
    data = xmltodict.parse(request.body)['xml']
    verify_notify_sign(data, key)
    pay_id = data['mch_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('zbtpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['err_code'])
    trade_no = data['plat_no']
    total_fee = float(data['order_amt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0为成功 其余为失败
    if trade_status == 0:
        _LOGGER.info('zbtpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'version': '1.0',
        'mch_code': app_id,
        'mch_no': str(pay_id),
        'sign_type': 'md5',
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    _LOGGER.info(u'zbtpay query: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['state'])  # 0 订单未成功 1订单成功
        total_fee = float(data['order_amt'])
        trade_no = data['system_no']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('zbtpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zbtpay data error, status_code: %s', response.status_code)


if __name__ == '__main__':
    p_dict = {
        'apiName': 'WAP_PAY_B2C',
        'apiVersion': '1.0.0.0',
        'platformID': '810001110013240',
        'merchNo': '810001110013240',
        'orderNo': '12323',
        'tradeDate': '20180111',
        'amt': '1.00',
        'merchUrl': 'http://zmkdkb.top.www.baidu.com',
        'merchParam': '123',
        'tradeSummary': 'charge',
    }
    sign_str = _gen_sign_str(p_dict)
    print sign_str
    p_dict['signMsg'] = _generate_sign(sign_str + '58678e4d81dde663c8dd9fc196913ad8')
    p_dict['choosePayType'] = '14'
    headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    response = requests.post(_GATEWAY, data=p_dict, headers=headers, timeout=10)
    print response.text
